<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use think\Loader;
use think\exception\HttpException;
use app\admin\Controller;
use think\Db;
use think\Config;
class Member extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];
	protected function filter(&$map)
    {
		$data=array('name'=>'name','card_num'=>'card_num','serial'=>'serial','mobile'=>'mobile');
		foreach ($data as $v)
		{
			if ($this->request->param($v)) {
				$map[$v] = ["like", "%" . $this->request->param($v) . "%"];
			}
		}
    }
    //提供给ajax一个生成好的序列号
    public function ajax_code(){
        $serial=$this->create_serial_code();
        echo $serial;
    }
	//序列号生成方法
	public function create_serial_code(){
		//序列号形式201712220001
		$date=date("Ymd");
		$counter=Db::name('counter')->where("date=$date")->find();
		if(empty($counter))
		{
			$serial_num=1;
		}
		else
		{
			$serial_num=$counter['counter']+1;  //在当天最大的序号基础上加1
		}
		$serial=$date.$this->serial_prefix($serial_num);
		return $serial;
	}
	//把小于4位数的序列号在前面填充0
	public function serial_prefix($serial_num){
		if($serial_num>0&&$serial_num<10)
			return '000'.$serial_num;
		else if($serial_num>=10&&$serial_num<100)
			return '00'.$serial_num;
		else if($serial_num>=100&&$serial_num<1000)
			return '0'.$serial_num;
		else if($serial_num>=1000&&$serial_num<10000)
			return $serial_num;
		else
			die("无法生成正确序列号");
	}
	//当天序号增加,返回插入序列的操作成败结果
	public function increase_serial(){
		$date=date("Ymd");
		$rs=false;
		$counter=Db::name('counter')->where("date=$date")->find();
		if(empty($counter))  //添加当天第一个序号时，新增当天第一个数据。否在在当天的数据基础上序列号+1，生成新的序列号。
		{
			$data['date']=$date;
			$data['counter']=1;
			$rs=Db::name('counter')->insert($data);
		}
		else
		{
			$rs=Db::name('counter')->where('date',$date)->setInc('counter');
		}
		return $rs;
	}
	//打印页
	public function print_table(){
		$print_info_id=1;
		$info=Db::name('print_table')->where("id=$print_info_id")->find();
		if(!empty($info))
		{
			$uid=input("id/d");
			if(!empty($uid))
			{
				$map['id']=$uid;
				$map['isdelete']=0;
				$member=Db::name('member')->where($map)->find();
				if(!empty($member))
				{
					$card_type=Db::name('brand')->where("status >0 and isdelete=0")->order('sort')->select(); //申请车型列表
					$this->view->assign('card_type',$card_type);
					$member['avator']=str_replace("/cheguan/","",$member['avator']);  //头像字符替换
					$this->view->assign('member',$member);
					$this->view->assign('info',$info);
					return $this->view->fetch();
				}else
				{
					$r=array('msg'=>'查询不到用户信息!');
					return ajax_return_adv_error($r);
				}
				
			}
			else
			{
				$r=array('msg'=>'请传入参数用户ID');
				return ajax_return_adv_error($r);
			}
		}else
		{
			$r=array('msg'=>'找不到打印表格信息');
			return ajax_return_adv_error($r);
		}
	}
	/**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->except(['id']);
            //生成一个序列号
            $serial=$this->create_serial_code();  //以这里生成的为准，避免预先生成的因多台电脑同时使用的时候造成重复
            $data['serial']=$serial;
            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 写入数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                //使用模型写入，可以在模型中定义更高级的操作
                $model = new $modelClass();
                $ret = $model->isUpdate(false)->save($data);
				$this->increase_serial();//记录序列号
            } else {
                // 简单的直接使用db写入
                Db::startTrans();
                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->insert($data);
					$this->increase_serial();//记录序列号
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }
            return ajax_return_adv('添加成功');
        } else {
            // 添加
			$serial=$this->create_serial_code(); //生成一个序列号
			$this->view->assign('serial',$serial);
			$card_type=Db::name('brand')->where("status >0 and isdelete=0")->order('sort')->select(); //申请车型列表
			$this->view->assign('card_type',$card_type);
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 更新数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                // 使用模型更新，可以在模型中定义更高级的操作
                $model = new $modelClass();
                $ret = $model->isUpdate(true)->save($data, ['id' => $data['id']]);
            } else {
                // 简单的直接使用db更新
                Db::startTrans();
                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->where('id', $data['id'])->update($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv("编辑成功");
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel($controller)->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }
			if(empty($vo['serial']))
				$vo['serial']=$this->create_serial_code(); //生成一个序列号
            $this->view->assign("vo", $vo);
			$card_type=Db::name('brand')->where("status >0 and isdelete=0")->order('sort')->select(); //申请车型列表
			$this->view->assign('card_type',$card_type);
            return $this->view->fetch();
        }
    }
    
}
